/*
 * $RCSfile: WebcatServlet.java,v $
 * $Revision: 1.1 $
 * $Date: 2013-03-19 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.webcat.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.j2ee.util.JsonUtil;
import com.skin.webcat.database.sql.Sql6;
import com.skin.webcat.database.sql.SqlResult;
import com.skin.webcat.util.Jdbc;
import com.skin.webcat.util.Webcat;

/**
 * <p>Title: WebcatServlet</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class WebcatServlet {
    private static final Logger logger = LoggerFactory.getLogger(WebcatServlet.class);

    /**
     * @param request
     * @param response
     * @param name
     * @param sql
     * @throws ServletException
     * @throws IOException
     */
    public static void execute(HttpServletRequest request, HttpServletResponse response, String name, String sql) throws ServletException, IOException {
        execute(request, response, name, (String)null, sql);
    }

    /**
     * @param request
     * @param response
     * @param name
     * @param database
     * @param sql
     * @throws ServletException
     * @throws IOException
     */
    public static void execute(HttpServletRequest request, HttpServletResponse response, String name, String database, String sql) throws ServletException, IOException {
        Connection connection = null;
        logger.info("sql: {}", sql);

        try {
            if(database == null) {
                connection = Webcat.getConnection(name);
            }
            else {
                connection = Webcat.getConnection(name, database);
            }

            SqlResult sqlResult = Sql6.execute(connection, sql);
            JsonUtil.callback(request, response, sqlResult);
            return;
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
            JsonUtil.error(request, response, 500, "系统错误，请稍后再试！");
        }
        finally {
            Jdbc.close(connection);
        }
    }
}
